package com.tyylab.kestrel.framework.spring.rpc.feign.impl;

import com.tyylab.kestrel.framework.util.HeaderPropagationConfig;
import com.tyylab.kestrel.framework.util.ContextUtil;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Feign header interceptor for propagating context headers
 * Adds tenant_id, request_id and other configured headers to Feign requests
 * 
 * @author tyylab
 */
@Component
@Slf4j
public class FeignHeaderInterceptor implements feign.RequestInterceptor {
    
    @Override
    public void apply(RequestTemplate template) {
        // Get all context values
        Map<String, Object> context = ContextUtil.getAll();
        
        // Add configured headers to the request
        for (Map.Entry<String, Object> entry : context.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            
            // Check if this header should be propagated
            if (HeaderPropagationConfig.shouldPropagate(key) && value != null) {
                String headerValue = value.toString();
                if (!headerValue.trim().isEmpty()) {
                    template.header(key, headerValue);
                    log.debug("Added header to Feign request: " + key + " = " + headerValue);
                }
            }
        }
    }
} 